package initialize

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"goods_srv/global"
	"goods_srv/model"
)

func InitEs() {

	host := fmt.Sprintf("http://%s:%d", "127.0.0.1", 9201)

	global.EsClient, err = elastic.NewClient(elastic.SetURL(host), elastic.SetSniff(false))
	if err != nil {
		zap.S().Panic(err)
	}

	exists, err := global.EsClient.IndexExists(model.EsGoods{}.GetIndexName()).Do(context.Background())
	if err != nil {
		zap.S().Panic(err)
	}

	if !exists {
		// Create a new index.
		_, err := global.EsClient.CreateIndex(model.EsGoods{}.GetIndexName()).BodyString(model.EsGoods{}.GetMapping()).Do(context.Background())
		if err != nil {
			zap.S().Panic(err)
		}
		//同步数据
		model.EsGoods{}.MysqlToEs()
	}

}
